package com.ddstation.onsitelaw.controller;

import com.ddstation.onsitelaw.entity.DtHealthManageInstitutionEntity;
import com.ddstation.onsitelaw.entity.DtSupervisorEnforcementEntity;
import com.ddstation.onsitelaw.entity.MaInvsViolationMessageEntity;
import com.ddstation.onsitelaw.model.AccountModel;
import com.ddstation.onsitelaw.service.AuditPrescriptionService;
import com.ddstation.onsitelaw.service.ViolationRecordService;
import com.ddstation.onsitelaw.utils.DateUtil;
import com.ddstation.onsitelaw.utils.PageResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.inject.Inject;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @author 陆青龙
 */
@Controller
public class ViolationRecordController {

    private static final Logger logger = LoggerFactory.getLogger(ViolationRecordController.class);

    @Inject
    private ViolationRecordService violationRecordService;


    @Inject
    private AuditPrescriptionService auditPrescriptionService;

    /**
     * 健康机构违规详情页面
     */
    @RequestMapping(value = "violationRecord")
    String drugsQuery(HttpSession session, Model model, @RequestParam("institutionId") String institutionId, @RequestParam("institutionName") String institutionName) {
        model.addAttribute("institutionId", institutionId);
        model.addAttribute("institutionName", institutionName);
        return "app/violationRecord";
    }

    /**
     * 违规列表
     */
    @RequestMapping(value = "violationRecord/violationRecordList")
    @ResponseBody
    Map<String, Object> violationRecordList(HttpSession session, @RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize") Integer pageSize, @RequestParam("institutionId") String institutionId, @RequestParam("flg") String flg) {

        Map<String, Object> map = new HashMap<>();
        map.put("errCode", 0);
        map.put("errMsg", "成功！");
        //获取session登录信息
        AccountModel account = (AccountModel) session.getAttribute("account");

        if (account == null || account.getSupervisorId() == null) {
            map.put("errCode", -1);
            map.put("errMsg", "服务器繁忙，请稍后再试。");
            return map;
        }
        List<String> ids = new ArrayList<>();
        if (!StringUtils.isEmpty(institutionId)) {
            ids.add(institutionId);
        } else {
            if (account.getRoleId() == 1) {
                List<DtHealthManageInstitutionEntity> healthManageList = account.getDtHealthManageInstitutionEntityList();
                ids = healthManageList.stream().map(i -> i.getId()).collect(Collectors.toList());
            }
            if (account.getRoleId() == 2) {
                List<DtSupervisorEnforcementEntity> supervisorEnforcements = account.getEnforcementList();
                ids = supervisorEnforcements.stream().map(i -> i.getHealthManageId()).collect(Collectors.toList());
            }
        }
        Integer uploaderId = account.getSupervisorId();
        //flg值为1。查看所有
        if ("1".equals(flg)) {
            uploaderId = null;
        }
        PageResult pageResult = violationRecordService.selectViolationRecord(account.getManageInstitutionEntity().getCounty(), pageNum, pageSize, ids, uploaderId);
        map.put("violationManageModelList", pageResult.getRows());
        map.put("total", pageResult.getTotal());

        Integer num = auditPrescriptionService.getManualAuditNum(account.getInstitutionId(), ids);
        map.put("num", "(待人核:" + num + "份)");
        return map;
    }


    /**
     * 违规健康机构列表
     */
    @RequestMapping(value = "violationRecord/manageViolationList")
    @ResponseBody
    Map<String, Object> manageViolationList(HttpSession session, @RequestParam("institutionId") String institutionId, @RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize") Integer pageSize) {

        Map<String, Object> map = new HashMap<>();
        map.put("errCode", 0);
        map.put("errMsg", "成功！");
        //获取session登录信息
        AccountModel account = (AccountModel) session.getAttribute("account");

        if (account == null || account.getSupervisorId() == null) {
            map.put("errCode", -1);
            map.put("errMsg", "服务器繁忙，请稍后再试。");
            return map;
        }
        List<String> institutionIds = new ArrayList<>();
        if (!StringUtils.isEmpty(institutionId)) {
            institutionIds.add(institutionId);
        } else {
            if (account.getRoleId() == 1) {
                List<DtHealthManageInstitutionEntity> healthManageList = account.getDtHealthManageInstitutionEntityList();
                institutionIds = healthManageList.stream().map(i -> i.getId()).collect(Collectors.toList());
            }
            if (account.getRoleId() == 2) {
                List<DtSupervisorEnforcementEntity> supervisorEnforcements = account.getEnforcementList();
                institutionIds = supervisorEnforcements.stream().map(i -> i.getHealthManageId()).collect(Collectors.toList());
            }
        }
        PageResult pageResult = violationRecordService.manageViolationList(institutionIds, account.getManageInstitutionEntity().getCounty(), pageNum, pageSize);
        map.put("manageViolationList", pageResult.getRows());
        map.put("total", pageResult.getTotal());
        return map;
    }


    /**
     * 跳转违规查询页
     */
    @RequestMapping(value = "violationQuery")
    String violationQuery(HttpSession session, Model model) {
        //获取session登录信息
        AccountModel account = (AccountModel) session.getAttribute("account");
        if (account == null || account.getSupervisorId() == null) {
            //session无登录信息返回登录页
            model.addAttribute("code", -1);
            model.addAttribute("msg", "登录状态已失效，请重新登录!");
        }

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        // 获取当天
        Calendar cale = Calendar.getInstance();
        String lastday = format.format(cale.getTime());
        //取开始时间 0：今日  1：本周
        String firstday = DateUtil.getFirstday(1);

        // 开始时间
        model.addAttribute("dtFrom", firstday);
        // 当天
        model.addAttribute("dtTo", lastday);

        List<MaInvsViolationMessageEntity> violationMessageList = violationRecordService.selectList();
        if (ObjectUtils.isEmpty(violationMessageList)) {
            throw new RuntimeException("master表【ma_invs_violation_message】没有数据！");
        }

        model.addAttribute("violationMessageList", violationMessageList);
        return "violationQuery";
    }


    /**
     * 违规记录查询接口
     *
     * @return
     */
    @RequestMapping(value = "violationRecord/loadPrescriptionViolateList", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> loadPrescriptionViolateList(
            @RequestParam String dtFrom,
            @RequestParam String dtTo,
            @RequestParam(required = false) Integer type,
            @RequestParam(required = false) String institutionName,
            @RequestParam String pageNum,
            @RequestParam String pageSize,
            HttpSession session) {
        Map<String, Object> ret = new HashMap<>();
        ret.put("errcode", -1);
        ret.put("errMsg", "系统出错，请稍后再试！");
        //获取session登录信息
        AccountModel account = (AccountModel) session.getAttribute("account");
        if (account == null || account.getSupervisorId() == null) {
            //session无登录信息返回登录页
            ret.put("code", -1);
            ret.put("msg", "登录状态已失效，请重新登录!");
        }
        List<String> healthManageInstitutionIds = null;
        if (account.getRoleId() == 1) {
            List<DtHealthManageInstitutionEntity> healthManageList = account.getDtHealthManageInstitutionEntityList();
            healthManageInstitutionIds = healthManageList.stream().map(i -> i.getId()).collect(Collectors.toList());
        }
        if (account.getRoleId() == 2) {
            List<DtSupervisorEnforcementEntity> supervisorEnforcements = account.getEnforcementList();
            healthManageInstitutionIds = supervisorEnforcements.stream().map(i -> i.getHealthManageId()).collect(Collectors.toList());
        }
        HashMap paramMap = new HashMap();
        paramMap.put("dtFrom", dtFrom);
        paramMap.put("dtTo", dtTo);
        paramMap.put("type", type);
        paramMap.put("institutionName", institutionName);
        paramMap.put("pageNum", pageNum);
        paramMap.put("pageSize", pageSize);
        paramMap.put("institutionIds", healthManageInstitutionIds);
        PageResult pageResult = violationRecordService.selectViolationListForPC(paramMap);
        ret.put("violationList", pageResult.getRows());
        ret.put("total", pageResult.getTotal());
        ret.put("pages", pageResult.getPages());
        ret.put("errcode", 0);
        ret.put("errMsg", "请求成功！");
        return ret;
    }
}